package com.example.ppjoke.frame.dynamicnav;

import android.content.res.AssetManager;

import com.example.ppjoke.App;
import com.example.ppjoke.frame.FrameActivity;
import com.example.ppjoke.frame.dynamicnav.entity.DestinationEntity;
import com.example.ppjoke.frame.dynamicnav.entity.FrameTabsEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.HashMap;

public class AppConfig {
    private AppConfig() {
        try {
            initData();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static AppConfig instance;

    public static AppConfig getInstance() {
        if (instance == null)
            instance = new AppConfig();
        return instance;
    }

    public FrameTabsEntity frameTabsEntity;
    public HashMap<String, DestinationEntity> destinationMap;

    public String readAssets(String path, AssetManager manager) throws IOException {
        String result = null;
        InputStream inputStream = manager.open(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = br.readLine())!=null)
            buffer.append(line);
        br.close();
        result = buffer.toString();
        return result;
    }

    public void initData() throws IOException {
        AssetManager manager = App.getInstance().getAssets();
        String mainResult = readAssets("main_tabs_config.json", manager);
        String destinationResult = readAssets("destination.json", manager);
        frameTabsEntity = new Gson().fromJson(mainResult, FrameTabsEntity.class);
        Type type = new TypeToken<HashMap<String, DestinationEntity>>() {}.getType();
        destinationMap = new Gson().fromJson(destinationResult, type);


    }
}
